//
//  GMPlayerViewController.m
//  Teecloud
//
//  Created by 小熊 on 2018/6/13.
//  Copyright © 2018年 小熊. All rights reserved.
//

#import "GMPlayerViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ZFAVPlayerManager.h"
#import "ZFPlayerControlView.h"
#import "GMQustionVC.h"
#import "GMCommentVC.h"
#import "GMKnowlegeVC.h"
#import "GMNoteVC.h"
#import "GMCommentBaseModel.h"
#import "GMExamInStudy.h"
#import "GMVideoExerciseVC.h"
#import "GMExercisesVC.h"
#import "GMEnclosureVC.h"
#import "GMLookPDFVC.h"
#import "GMShareVC.h"
#import <AVFoundation/AVPlayer.h>
@interface GMPlayerViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *containerView;
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@property (nonatomic, strong) NSArray *titArr;
@property (weak, nonatomic) IBOutlet UIView *titView;
@property (weak, nonatomic) IBOutlet UIScrollView *contentScrollView;
/* 上一次选择的按钮 */
@property (weak , nonatomic)UIButton *lastSelectButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollviewBottom;
@property (weak, nonatomic) IBOutlet UIButton *firstBtn;
/**播放数*/
@property (weak, nonatomic) IBOutlet UILabel *playCount;
/**习题数*/
@property (weak, nonatomic) IBOutlet UILabel *etrat;
/**附件数*/
@property (weak, nonatomic) IBOutlet UILabel *fujian;
@property (nonatomic, strong) GMCommentBaseModel *baseModel;
/**当前播放时间*/
@property (nonatomic, assign) NSTimeInterval curentTime;

@property (weak, nonatomic) IBOutlet UIButton *playBtn;

@property (nonatomic, strong) ZJTimeCountDown *timeCount;

@property (nonatomic, strong) NSArray <NSURL *>*assetURLs;
//最后播放时间
@property (nonatomic, assign) NSInteger lastTime;

@end
/** 重用cell ID */
static NSString *const CollectionCell = @"CollectionCell";
/** 按钮tag附加值 */
#define BTNTAG 1000;
@implementation GMPlayerViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.player.viewControllerDisappear = NO;
    if (self.lastSelectButton) {
         [self selectBtn:self.lastSelectButton];
    }
   
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.player.viewControllerDisappear = YES;
    if (self.lastSelectButton) {
        [self selectBtn:self.lastSelectButton];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addLeftBarButtonWithImage:[UIImage imageNamed:@"left-white-64"] action:@selector(left_BarButtonItemAction)];
    [self addRightBarButtonWithFirstImage:[UIImage imageNamed:@"share_white"] action:@selector(share_white)];
    self.contentScrollView.frame= CGRectMake(0, 0, DEVICE_WIDTH, _contentScrollView.zj_height);
    [self getCommentData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoPlay) name:@"gotoPlay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pausePlayer) name:@"comentPause" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playWithTheTime:) name:@"playWithTheTime" object:nil];
    _timeCount = [[ZJTimeCountDown alloc] init];

    
}
- (void)left_BarButtonItemAction {
    if (kIsEmptyString(self.typeStr)) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
/**从指定时间播放*/
-(void)playWithTheTime:(NSNotification *)noti{
    NSDictionary *dict = [noti object];
    NSTimeInterval begTime = [dict[@"playTime"] doubleValue];
//    NSTimeInterval endTime = [dict[@"endTime"] doubleValue];
    [self.player playTheIndex:0];
    [self.controlView showTitle:self.baseModel.Name coverURLString:self.baseModel.HeadUrl fullScreenMode:ZFFullScreenModeLandscape];
    [self.player seekToTime:begTime completionHandler:^(BOOL finished) {
        if (finished) {
            [self.player.currentPlayerManager play];
        }
    }];
}
//暂停播放
- (void)pausePlayer{
    [self.player.currentPlayerManager pause];
    NSDictionary *dict = @{@"curentTime":[NSString stringWithFormat:@"%.0f",self.curentTime]};
    //把当前的时间通过通知发送给需要时间的页面
    [[NSNotificationCenter defaultCenter] postNotificationName:@"postTime" object:dict];
}
//继续播放
-(void)gotoPlay{
    [self.player seekToTime:self.curentTime+1 completionHandler:^(BOOL finished) {
        if (finished) {
            [self updataplayCount];
            [self.player.currentPlayerManager play];
        }
    }];
}
- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        kWeakObject(self)
        _controlView = [ZFPlayerControlView new];
        _controlView.fastViewAnimated = YES;
        [_controlView.landScapeControlView setSliderValueChanged:^(CGFloat value) {
            //滑动结束
            [weakself.timeCount zj_timeDestoryTimer];
            weakself.curentTime = self.player.totalTime*value;
            [weakself updataplayCount];
            
        }];
        [_controlView.portraitControlView setSliderValueChanged:^(CGFloat value) {
            //滑动结束
            [weakself.timeCount zj_timeDestoryTimer];
            weakself.curentTime = self.player.totalTime*value;
            [weakself updataplayCount];
        }];
     
    }
    return _controlView;
}


#pragma mark - 添加所有子控制器
- (void)setUpAllChildViewController{
    GMCommentVC *comment = [[GMCommentVC alloc] init];
    comment.resId = self.resId;
    [self addChildViewController:comment];
    GMQustionVC *question = [[GMQustionVC alloc] init];
    question.resId = self.resId;
    [self addChildViewController:question];
    GMKnowlegeVC *know =[[GMKnowlegeVC alloc] init];
    know.dataArr = self.baseModel.Dirs;
    [self addChildViewController:know];
    GMNoteVC *note = [[GMNoteVC alloc] init];
    note.resId = self.resId;
    [self addChildViewController:note];
    [self selectBtn:self.firstBtn];
}
- (void)getCommentData{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.resId forKey:@"resId"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:self.packId forKey:@"packId"];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetResDetail&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMCommentBaseModel *comModel = [GMCommentBaseModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                self.baseModel = comModel;
                [self setUpAllChildViewController];
                self.title = comModel.Name;
                self.playCount.text = [NSString stringWithFormat:@"%@",comModel.PlayCount];
                self.etrat.text =[NSString stringWithFormat:@"%@/%@",comModel.Count,comModel.ExerCount];
                self.fujian.text =[NSString stringWithFormat:@"%ld",comModel.AttachList.count?comModel.AttachList.count:0];
                if ([comModel.ExerCount isEqualToNumber:@(0)]) {
                    self.etrat.textColor = kDarkGrayColor;
                }else{
                    self.etrat.textColor = [UIColor colorWithHexString:@"007AFF"];
                }
                if (comModel.AttachList.count ==0) {
                    self.fujian.textColor = kDarkGrayColor;
                }else{
                     self.fujian.textColor = [UIColor colorWithHexString:@"007AFF"];
                }
                [self.containerView yy_setImageWithURL:[NSURL URLWithString:comModel.HeadUrl] placeholder:DefealtImg];
                ZFAVPlayerManager *playerManager = [[ZFAVPlayerManager alloc] init];
                /// 播放器相关
                self.player = [ZFPlayerController playerWithPlayerManager:playerManager containerView:self.containerView];
                self.player.controlView = self.controlView;
                self.player.controlView.
                /// 设置退到后台继续播放
                self.player.pauseWhenAppResignActive = NO;
                kWeakObject(self)
                self.player.orientationWillChange = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {

                    [weakself setNeedsStatusBarAppearanceUpdate];
                };
                /// 播放完成
                self.player.playerDidToEnd = ^(id  _Nonnull asset) {
                    [weakself updataPlayEnd];
                    weakself.playBtn.hidden = NO;
                    [weakself.player.currentPlayerManager stop];
                };
                self.player.playerPrepareToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
                       weakself.playBtn.hidden = YES;
                };
                self.player.playerReadyToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
                    weakself.playBtn.hidden = YES;
                    [weakself updataplayCount];
                };
                self.player.playerPlayStateChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, ZFPlayerPlaybackState playState) {
                    switch (playState) {
                        case ZFPlayerPlayStatePaused:{
                            //暂停播放
                             [weakself.timeCount zj_timeDestoryTimer];
                        }
                            break;
                        case ZFPlayerPlayStatePlayFailed:{
                            //播放失败
                              [weakself.timeCount zj_timeDestoryTimer];
                        }
                            break;
                        case ZFPlayerPlayStatePlayStopped:{
                            //停止播放
                              [weakself.timeCount zj_timeDestoryTimer];
                        }
                            break;
                        case ZFPlayerPlayStatePlaying:{
                            //正在播放
                            [weakself updataplayCount];
                        }
                            break;
                            
                        default:
                            break;
                    }
                };

                //播放时间回调
               __block NSInteger tepTime = 0;
                self.player.playerPlayTimeChanged = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSTimeInterval currentTime, NSTimeInterval duration) {
                    weakself.curentTime = currentTime;
                    NSInteger conTime = round(currentTime);
                    if(tepTime<conTime){
                        tepTime=conTime;
                        for (NSInteger i=0; i<comModel.ExamInStudy.count; i++) {
                            GMExamInStudy *study = comModel.ExamInStudy[i];
                            if (study.PointTime == tepTime) {
                                if (weakself.player.orientationObserver.supportInterfaceOrientation & ZFInterfaceOrientationMaskPortrait) {
                                    [weakself.player enterFullScreen:NO animated:YES];
                                }
                                //暂停播放
                                [weakself.player.currentPlayerManager pause];
//                                NSLog(@"插入题目");
                                GMVideoExerciseVC *exercise = [[GMVideoExerciseVC alloc] init];
                                exercise.stuModel = study;
                                exercise.resId = weakself.resId;
                                [weakself presentViewController:exercise animated:YES completion:nil];
                            }
                    }
                }
            };
                if (self.baseModel.IsOnlyOrderPlay) {
                    self.controlView.landScapeControlView.slider.userInteractionEnabled = NO;
                    self.controlView.portraitControlView.slider.userInteractionEnabled = NO;
                }
                self.assetURLs = @[[NSURL URLWithString:comModel.Url]];
                self.player.assetURLs = self.assetURLs;
               
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"请求出错" toView:self.view];
        }
    }];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (self.player.isFullScreen) {
        return UIStatusBarStyleLightContent;
    }
    return UIStatusBarStyleDefault;
}

- (BOOL)prefersStatusBarHidden {
    /// 如果只是支持iOS9+ 那直接return NO即可，这里为了适配iOS8
    return self.player.isStatusBarHidden;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationSlide;
}

- (BOOL)shouldAutorotate {
    return self.player.shouldAutorotate;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.player.isFullScreen) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskPortrait;
}

- (IBAction)selectBtn:(UIButton *)sender {
     NSInteger buttonTag = sender.tag - BTNTAG;
    [self selectButton:sender];
    //添加控制器View
    [self AddOneVcWithButtton:buttonTag];
    //滚动到相应的位置
    _contentScrollView.contentOffset = CGPointMake(buttonTag * DEVICE_WIDTH, 0);
}
#pragma mark - 选中标题
- (void)selectButton:(UIButton *)button{
    _lastSelectButton.transform = CGAffineTransformIdentity; //还原
    _lastSelectButton.selected = NO;
    button.selected =YES;
    _lastSelectButton = button;
}
//添加控制器View
- (void)AddOneVcWithButtton:(NSInteger)i{
    UIViewController *vc = self.childViewControllers[i];
    if (vc.view.superview)return;
    vc.view.frame = CGRectMake(i * DEVICE_WIDTH, 0 ,DEVICE_WIDTH , _contentScrollView.zj_height);
    [self.contentScrollView addSubview:vc.view];
}
-(void)share_white{
    XZShareController *shareVC = [[XZShareController alloc] init];
    shareVC.shareTitle = self.baseModel.Name;
    shareVC.shareContent = self.baseModel.FromName;
    shareVC.shareUrl =self.baseModel.Url;
    shareVC.shareImgUrl = self.baseModel.HeadUrl;
    shareVC.resId = self.resId;
    [self.navigationController presentSemiViewController:shareVC withOptions:@{
                                                                               KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                               KNSemiModalOptionKeys.animationDuration : @(0.6),
                                                                               KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                               }];
}
/**习题点击事件*/
- (IBAction)xitibtnClick:(id)sender {
    
    if (![self.baseModel.ExerCount isEqualToNumber:@(0)]) {
        GMExercisesVC *vc = [[GMExercisesVC alloc] init];
        vc.resId = self.resId;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
/**附件点击事件*/
- (IBAction)fujianBtnClick:(id)sender {
   
    if (self.baseModel.AttachList.count >0) {
        //发送通知，暂停播放
        [[NSNotificationCenter defaultCenter] postNotificationName:@"comentPause" object:nil];
        kWeakObject(self)
        GMEnclosureVC *vc = [[GMEnclosureVC alloc] init];
        vc.encolseureBlock = ^(GMAttachListModel *model) {
            GMLookPDFVC *preVc = [[GMLookPDFVC alloc] init];
            preVc.model = model;
            [weakself.navigationController pushViewController:preVc animated:YES];
        };
        vc.dataArr = self.baseModel.AttachList;
        [self.navigationController presentSemiViewController:vc withOptions:@{
                                                                                   KNSemiModalOptionKeys.pushParentBack    : @(NO),
                                                                                   KNSemiModalOptionKeys.animationDuration : @(0.6),
                                                                                   KNSemiModalOptionKeys.shadowOpacity     : @(0.3)
                                                                                   }];
    }
}
/**更新播放记录*/
- (void)updataplayCount{
    kWeakObject(self)
    [_timeCount zj_timeCountUPWithCurrentTime:self.curentTime interval:5 completeBlock:^(NSInteger hour, NSInteger minute, NSInteger second) {
        NSInteger temp = hour *3600+ minute *60 +second;
        [weakself updataPlayWithSecond:temp];
    }];
}
- (void)updataPlayWithSecond:(NSInteger)second{
    self.lastTime = second;
    if (self.baseModel.TimeLen - second <=5){
        [self.timeCount zj_timeDestoryTimer];
        return;
    }
    NSInteger playLenth = 5;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"resId":self.resId,
                          @"playStart":@(second),
                          @"playLength":@(playLenth)
                          };
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=UpdatePlayRecord&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
              
            }
        }
    }];
}
/**播放结束更新播放记录*/
- (void)updataPlayEnd{
    NSInteger playLenth = self.baseModel.TimeLen -self.lastTime;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"resId":self.resId,
                          @"playStart":@(self.lastTime),
                          @"playLength":@(playLenth)
                          };
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=UpdatePlayRecord&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                
            }
        }
    }];
}
- (IBAction)playClick:(id)sender {
    if (self.baseModel.LastPlayTime ==0 ) {
        [self.player playTheIndex:0];
        [self.controlView showTitle:self.baseModel.Name coverURLString:self.baseModel.HeadUrl fullScreenMode:ZFFullScreenModeLandscape];
    }else{
       
        if (self.baseModel.LastPlayTime > self.baseModel.TimeLen || self.baseModel.IsPlayOver) {
            [self.player playTheIndex:0];
            [self.controlView showTitle:self.baseModel.Name coverURLString:self.baseModel.HeadUrl fullScreenMode:ZFFullScreenModeLandscape];
        }else{
            if (self.playSecond) {
                //如果有记录播放时间，直接从这个时间开始播放
                [self.player playTheIndex:0];
                [self.controlView showTitle:self.baseModel.Name coverURLString:self.baseModel.HeadUrl fullScreenMode:ZFFullScreenModeLandscape];
                [self.player seekToTime:self.playSecond completionHandler:^(BOOL finished) {
                    if (finished) {
                        [self.player.currentPlayerManager play];
                    }
                }];
            }else{
                NSString *timeStr = [self getMMSSFromSS:self.baseModel.LastPlayTime];
                NSString *msg = [NSString stringWithFormat:@"您上次观看到%@，是否从上次播放点开始播放?",timeStr];
                UIAlertController *alert = [UIAlertController zj_alertControllerWithTitle:@"记忆播放" message:msg optionStyle:OptionStyleStyleOK_Cancel OkTitle:@"记忆播放" cancelTitle:@"重头播放" okBlock:^{
                    self.curentTime = self.baseModel.LastPlayTime;
                    [self.player playTheIndex:0];
                    [self.controlView showTitle:self.baseModel.Name coverURLString:self.baseModel.HeadUrl fullScreenMode:ZFFullScreenModeLandscape];
                    [self.player seekToTime:self.baseModel.LastPlayTime completionHandler:^(BOOL finished) {
                        if (finished) {
                            [self.player.currentPlayerManager play];
                        }
                    }];
                } cancelBlock:^{
                    [self.player playTheIndex:0];
                    [self.controlView showTitle:self.baseModel.Name coverURLString:self.baseModel.HeadUrl fullScreenMode:ZFFullScreenModeLandscape];
                }];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
        
    }
  
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSInteger )totalTime{
    
    NSInteger seconds = totalTime;
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@分%@秒",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
    
}

- (void)dealloc {
    [_timeCount zj_timeDestoryTimer];
    NSLog(@"%@释放了",self.class);
}
@end
